# -*- coding: utf-8 -*-

from PyQt5 import QtCore, QtGui, QtWidgets, Qt
from PyQt5.QtCore import QTimer
from pageTest1 import pageNewTest, JobCfgItem
from testResult import PageTestReuslt
from TestCfgDB import TestCfgDB

from NumKeyBoard import NumKeyBoard

from SerialProbe import SerialProbe
from SerialStm32 import SerialStm32

from MyIconButton import MyIconButton

from pageCopyData import pageCoyData

class Window(QtWidgets.QMainWindow):

   portNameProbe1 = "COM10"
   portNameProbe2 = "COM11"
   portNameStm32 = "COM5"

   JobTimerInterval = 200

   def __init__(self):
      super().__init__()
      self.testCfg = TestCfgDB()
      self.resultPage = PageTestReuslt()
      self.jobTimer = QTimer()
      self.jobTimer.timeout.connect(self.testJobExcute)
      self.resultPage.btnStopTest.clicked.connect(self.stopTest)
      self.pageIndex = 0
      self.setGeometry(0, 0, 1280, 800)
      self.create_toolbar()
      self.set_homepage()
      self.setWindowState(self.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)
      self.setWindowFlags(QtCore.Qt.FramelessWindowHint|QtCore.Qt.WindowStaysOnTopHint|QtCore.Qt.Window)
      self.setWindowFlags(QtCore.Qt.FramelessWindowHint|QtCore.Qt.Window)
      self.show()

      self.readBackTemp1 = 0.0
      self.readBackTemp2 = 0.0

      self.measureJobIndex = 0
      self.measureJobState = 0

      self.dataProbe1 = 0.0
      self.dataProbe2 = 0.0

      self.kb = NumKeyBoard(callback=self)
      self.focused_input = None

      self.timeConsumed = 0

   def on_key(self, keys):
      if self.focused_input is not None:
         self.focused_input.setText(keys)

   def create_toolbar(self):
      tb = self.addToolBar('File')
      tb.setMovable(False)
      tb.setFixedHeight(60)
      tb.setIconSize(Qt.QSize(60, 60))
      action_screenshot = QtWidgets.QAction(QtGui.QIcon("./images/screen.png"), "Take a screen shot", self)
      action_goback = QtWidgets.QAction(QtGui.QIcon("./images/back.png"), "Back to previous page", self)
      action_goback.triggered.connect(self.back_to_prev)
      toolbar_spacing = Qt.QWidget()
      toolbar_spacing.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
      tb.addAction(action_screenshot)
      tb.addWidget(toolbar_spacing)
      tb.addAction(action_goback)

   def set_homepage(self):
      self.homepage = Qt.QWidget()
      layout_homepage = QtWidgets.QGridLayout()
      self.homepage.pButton1 = MyIconButton(btnTxt="新建实验", btnIcon="./images/newTest.png")
      self.homepage.pButton1.setFixedSize(200, 220)
      self.homepage.pButton2 = MyIconButton(btnTxt="查看结果", btnIcon="./images/reports.png")
      self.homepage.pButton2.setFixedSize(200, 220)
      self.homepage.pButton3 = MyIconButton(btnTxt="文件管理", btnIcon="./images/Files.png")
      self.homepage.pButton3.setFixedSize(200, 220)
      self.homepage.pButton4 = MyIconButton(btnTxt="系统设置", btnIcon="./images/Settings.png")
      self.homepage.pButton4.setFixedSize(200, 220)
      layout_homepage.addWidget(self.homepage.pButton1, 1, 1, 1, 1)
      layout_homepage.addWidget(self.homepage.pButton2, 1, 2, 1, 1)
      layout_homepage.addWidget(self.homepage.pButton3, 1, 3, 1, 1)
      layout_homepage.addWidget(self.homepage.pButton4, 2, 1, 1, 1)

      self.homepage.pButton1.clicked.connect(lambda: self.switch_central_widget(1))
      self.homepage.pButton2.clicked.connect(lambda: self.switch_central_widget(2))
      self.homepage.pButton3.clicked.connect(lambda: self.switch_central_widget(3))
      self.homepage.pButton4.clicked.connect(lambda: self.switch_central_widget(4))
      self.homepage.setLayout(layout_homepage)

      self.setCentralWidget(self.homepage)

   def switch_central_widget(self, page_index):
      if page_index == 0:
         self.set_homepage()
      if page_index == 1:

         self.setupNewTestPage()
      if page_index == 2:
         self.pageIndex = 2
         self.page2 = QtWidgets.QLabel("Page test result")
         self.setCentralWidget(self.page2)
      if page_index == 3:
         self.pageIndex = 3
         self.page3 = pageCoyData()
         self.setCentralWidget(self.page3)
      if page_index == 4:
         self.pageIndex = 4
         self.page4 = JobCfgItem(index=4)
         self.setCentralWidget(self.page4)

   def back_to_prev(self):
      if self.pageIndex != 0:
         self.pageIndex = 0
         self.switch_central_widget(0)
      else:
         Stm32.serialwork.com.close()
         Probe1.serialwork.com.close()
         Probe2.serialwork.com.close()
         if sys.platform != 'linux':
            self.close()

   def setupNewTestPage(self):
      self.pageIndex = 1
      self.page1 = pageNewTest(keyBoard_callback=self.lineEdit_clicked)
      self.page1.setStartTestCallBack(self.startTest)
      self.setTestPara()
      self.setCentralWidget(self.page1)
      self.page1.testPage3.TextCycleStart.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage3.TextCycleStart, e)
      self.page1.testPage3.TextCycleStop.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage3.TextCycleStop, e)
      self.page1.testPage3.TextCycleTimes.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage3.TextCycleTimes, e)
      self.page1.testPage4.TempHotCover.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.TempHotCover, e)
      self.page1.testPage4.melting1Start.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.melting1Start, e)
      self.page1.testPage4.melting1Stop.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.melting1Stop, e)
      self.page1.testPage4.melting2Start.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.melting2Start, e)
      self.page1.testPage4.melting2Stop.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.melting2Stop, e)
      self.page1.testPage4.MoveM1.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.MoveM1, e)
      self.page1.testPage4.MoveN1.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.MoveN1, e)
      self.page1.testPage4.MoveM2.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.MoveM2, e)
      self.page1.testPage4.MoveN2.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.MoveN2, e)
      self.page1.testPage4.Temp1Error.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.Temp1Error, e)
      self.page1.testPage4.Temp2Error.mousePressEvent = lambda e: self.lineEdit_clicked(self.page1.testPage4.Temp2Error, e)

   def lineEdit_clicked(self, editor, e):
      self.focused_input = editor
      self.kb.show()

   def startTest(self):
      self.testCfg.measureJobList=[]
      self.testCfg.SetSampelType(0, self.page1.testPage2.configSample1.currentIndex())
      self.testCfg.SetSampelType(1, self.page1.testPage2.configSample2.currentIndex())
      self.testCfg.SetSampelType(2, self.page1.testPage2.configSample3.currentIndex())
      self.testCfg.SetSampelType(3, self.page1.testPage2.configSample4.currentIndex())
      self.testCfg.SetSampelType(4, self.page1.testPage2.configSample5.currentIndex())
      self.testCfg.SetSampelType(5, self.page1.testPage2.configSample6.currentIndex())
      self.testCfg.SetSampelType(6, self.page1.testPage2.configSample7.currentIndex())
      self.testCfg.SetSampelType(7, self.page1.testPage2.configSample8.currentIndex())

      self.testCfg.SetHotCover(float(self.page1.testPage4.TempHotCover.text()))

      self.testCfg.SetMeasureParameter(Temp1Err = float(self.page1.testPage4.Temp1Error.text()),
                                       Temp2Err= float(self.page1.testPage4.Temp2Error.text()),
                                       Move1M = float(self.page1.testPage4.MoveM1.text()),
                                       Move1N = float(self.page1.testPage4.MoveN1.text()),
                                       Move2M = float(self.page1.testPage4.MoveM2.text()),
                                       Move2N = float(self.page1.testPage4.MoveN2.text()),)

      if self.testCfg.MeasureParameter['Temp1Err'] == 0.0:
         self.testCfg.MeasureParameter['Temp1Err'] = 0.5

      if self.testCfg.MeasureParameter['Temp2Err'] == 0.0:
         self.testCfg.MeasureParameter['Temp2Err'] = 0.5

      for item in self.page1.testPage3.items:
           self.testCfg.NewMeasureJob(index=int(item.labIndex.text()),
                                      temp=item.temp,
                                      time = item.keepTime,
                                      enable_probe1=item.isProbe1Enalbed,
                                      enable_probe2=item.isProbe2Enalbed
           )

      self.testCfg.SetMeasureRepeat(int(self.page1.testPage3.TextCycleStart.text()),
                                    int(self.page1.testPage3.TextCycleStop.text()),
                                    int(self.page1.testPage3.TextCycleTimes.text()))

      self.testCfg.SetMelting1Temp(self.page1.testPage4.enableMelting1.isChecked(),
                                   float(self.page1.testPage4.melting1Start.text()),
                                   float(self.page1.testPage4.melting1Stop.text()))

      self.testCfg.SetMelting2Temp(self.page1.testPage4.enabeMelting2.isChecked(),
                                   float(self.page1.testPage4.melting2Start.text()),
                                   float(self.page1.testPage4.melting2Stop.text()))

      self.resultPage.setGeometry(0, 0, 1280, 800)
      self.resultPage.setWindowFlag(QtCore.Qt.FramelessWindowHint)
      self.resultPage.show()
      self.runTest()

   def setTestPara(self):
      if self.testCfg.LoadYaml() == False:
         return;

      self.page1.testPage2.configSample1.setCurrentIndex(self.testCfg.sampleTypeList[0])
      self.page1.testPage2.configSample2.setCurrentIndex(self.testCfg.sampleTypeList[1])
      self.page1.testPage2.configSample3.setCurrentIndex(self.testCfg.sampleTypeList[2])
      self.page1.testPage2.configSample4.setCurrentIndex(self.testCfg.sampleTypeList[3])
      self.page1.testPage2.configSample5.setCurrentIndex(self.testCfg.sampleTypeList[4])
      self.page1.testPage2.configSample6.setCurrentIndex(self.testCfg.sampleTypeList[5])
      self.page1.testPage2.configSample7.setCurrentIndex(self.testCfg.sampleTypeList[6])
      self.page1.testPage2.configSample8.setCurrentIndex(self.testCfg.sampleTypeList[7])

      self.page1.testPage4.TempHotCover.setText(str(self.testCfg.TempHotCover))
      self.page1.testPage4.MoveM1.setText(str(self.testCfg.MeasureParameter['Move1M']))
      self.page1.testPage4.MoveN1.setText(str(self.testCfg.MeasureParameter['Move1N']))
      self.page1.testPage4.MoveM2.setText(str(self.testCfg.MeasureParameter['Move2M']))
      self.page1.testPage4.MoveN2.setText(str(self.testCfg.MeasureParameter['Move2N']))
      self.page1.testPage4.Temp1Error.setText(str(self.testCfg.MeasureParameter['Temp1Err']))
      self.page1.testPage4.Temp2Error.setText(str(self.testCfg.MeasureParameter['Temp2Err']))
      self.page1.testPage4.enableMelting1.setChecked(self.testCfg.MeltingCurve1['enabled'])
      self.page1.testPage4.melting1Start.setText(str(self.testCfg.MeltingCurve1['tempStart']))
      self.page1.testPage4.melting1Stop.setText(str(self.testCfg.MeltingCurve1['tempStop']))
      self.page1.testPage4.enabeMelting2.setChecked(self.testCfg.MeltingCurve2['enabled'])
      self.page1.testPage4.melting2Start.setText(str(self.testCfg.MeltingCurve2['tempStart']))
      self.page1.testPage4.melting2Stop.setText(str(self.testCfg.MeltingCurve2['tempStop']))

      self.page1.testPage3.TextCycleTimes.setText(str(self.testCfg.measureJobRepeat['repeatTimes']))
      self.page1.testPage3.TextCycleStart.setText(str(self.testCfg.measureJobRepeat['startIndex']))
      self.page1.testPage3.TextCycleStop.setText(str(self.testCfg.measureJobRepeat['stopIndex']))

      for i in self.testCfg.measureJobList:
         #setItem(self, index, temp, enalbe1, enable2, time=60):
         try:
            itemIndex = i['index']
         except:
            itemIndex = 0
         self.page1.testPage3.setItem(index=itemIndex,
                                      temp=str(i['temp']),
                                      enable1=i['probe1'],
                                      enable2=i['probe2'],
                                      time=int(i['time']))

   def runTest(self):
      self.testCfg.GenerateYaml()
      self.testCfg.PrintCfg()
      self.testJobStat = 0
      self.measureJobIndex = 0
      self.measureJobState = 0
      self.measureRepeatTimes = 0
      self.jobTimer.start(self.JobTimerInterval)
      print("Test start!")
      self.timeConsumed = 0

   def readRcvProbe1(self, rcvData):
      if rcvData['code'] == 1:
         self.dataProbe1 = rcvData['value']
      print(rcvData)

   def readRcvProbe2(self, rcvData):
      if rcvData['code'] == 1:
         self.dataProbe2 = rcvData['value']
      print(rcvData)

   def readRcvStm32(self, rcvData):
      if rcvData['code'] == Stm32.CODE_ERROR:
         self.readBackTemp1 = 0.0
         self.resultPage.textBrowser.append(Stm32.errorString(rcvData['value']))

      if rcvData['code'] == Stm32.CODE_TEMP1:
         self.readBackTemp1 = rcvData['value']
         self.resultPage.textBrowser.append("Current temp of sample %d:%f"%(self.measureJobIndex,
                                                                            rcvData['value']))

      if rcvData['code'] == Stm32.CODE_MOVE:
         self.probeMoveDone = True

      if rcvData['code'] == Stm32.CODE_TEMP2:
         self.readBackTemp2 = rcvData['value']
         self.resultPage.textBrowser.append("Current temp of hot cover:%f"%rcvData['value'])

   def testJobExcute(self):
      self.timeConsumed = self.timeConsumed + self.JobTimerInterval / 1000.0
      print("TestJob = %d, TimeConsumed(s)=%f"%(self.testJobStat, self.timeConsumed))

      '''
      Check if the delay after reset cmd is reached
      '''
      if self.testJobStat == 2 and self.counterForReset > 0:
         #self.resultPage.textBrowser.append("delay %d"%self.counterForReset)
         self.counterForReset = self.counterForReset - 1
         return

      '''
      Do test job as the defined sequence
      '''
      if self.testJobStat == 0 :
         '''
         send the cmd reset
         '''
         try:
            Stm32.serialwork.sendData(Stm32.sendCmdReset())
            self.resultPage.textBrowser.append("->cmd 'reset' has been sent")
            self.resultPage.textBrowser.append("Waiting for hardware init...")
            self.counterForReset = int(20000/self.JobTimerInterval)
            self.testJobStat = 2
         except:
            print("Something wrong when sending cmd reset!")
      elif self.testJobStat == 1:
         '''
         send the cmd 'move probe to origin'
         '''
         try:
            Stm32.serialwork.sendData(Stm32.sendMoveTo(0.0))
            self.resultPage.textBrowser.append("->cmd 'move to origin' sent")
            self.testJobStat = 2
         except:
            print("Something wrong when sending cmd set Temp1!")
      elif self.testJobStat == 2:
         '''
         send the cmd 'set hot cover temperature'
         '''
         try:
            Stm32.serialwork.sendData(Stm32.sendSetTemp2(self.testCfg.TempHotCover))
            self.resultPage.textBrowser.append("->cmd 'set hot cover temp' sent")
            self.testJobStat = 3

            self.readBackTemp2 = 0
         except:
            print("Something wrong when sending cmd set Temp1!")
      elif self.testJobStat == 3:
         '''
         send the cmd 'read hot cover temperature'
         uitil the last read back temp1 is in a proper range
         '''
         if self.isTemp2Reached(self.readBackTemp2):
            #if the temp1 reached, set to go to next job and return directly
            self.testJobStat = 4
            self.measureJobIndex = 0
            self.measureJobState = 0
            return
         try:
            Stm32.serialwork.sendData(Stm32.sendGetTemp2())
            self.resultPage.textBrowser.append("->cmd 'read hot cover temp', lastValue=%f"%self.readBackTemp2)
         except:
            print("Something wrong when sending cmd get Temp1!")
      elif self.testJobStat == 4:
         '''
         send the cmd 'read hot cover temperature'
         uitil the last read back temp1 is in a proper range
         '''
         self.processMeasureJob()
      elif self.testJobStat == 5:
         '''
         run the melting curve
         '''
         #self.getMeltingCurve()

         print("melting not suported now...")
         Probe1.stopReadData()
         Probe2.stopReadData()

   def processMeasureJob(self):
      # the measureJobIndex must be set to 0 before start testing
      jobItem = self.testCfg.measureJobList[self.measureJobIndex]

      if self.measureJobState == 0:
         '''
         Set temperature for the measure step n
         '''
         try:
            Stm32.serialwork.sendData(Stm32.sendSetTemp1(jobItem['temp']))
            self.resultPage.textBrowser.append("==> Step %d, cmd 'set sample temp' sent"%self.measureJobIndex)
            self.measureJobState = 1
            self.readBackTemp1 = 0
         except:
            print("Something wrong when sending cmd set sample temp2!")

      elif self.measureJobState == 1:
         '''
         Check if the target temperature for the measure step n
         '''
         if self.isTemp1Reached(self.readBackTemp1, jobItem['temp']):
            #if the temp1 reached, set to go to next job and return directly
            self.measureJobState = 2
            self.counterForMeasure = int(jobItem['time'] * 1000/self.JobTimerInterval)
            self.resultPage.textBrowser.append("==> Step %d, Temp is reached, Temp=%f"%(self.measureJobIndex, self.readBackTemp1))
            return

         try:
            Stm32.serialwork.sendData(Stm32.sendGetTemp1())
            self.resultPage.textBrowser.append("==> Step %d, cmd 'get sample temp', lastValue=%f"%(self.measureJobIndex, self.readBackTemp1))
            print("Sample Temp now: ", self.readBackTemp1)
         except:
            print("Something wrong when sending cmd get Temp2!")

      elif self.measureJobState == 2:
         '''
         Keep xxxx seconds after the temperature is reached for the measure step n
         '''
         if self.counterForMeasure > 0:
            self.counterForMeasure = self.counterForMeasure - 1
            print("Delay after temp2 is reached... %d"%self.counterForMeasure)
         else:
            self.sensorDataState = 0
            self.sampleReadIndex = 0
            self.readSensorDataDone = False
            if jobItem['probe1'] == True:
               self.measureJobState = 3
               self.resultPage.textBrowser.append("==> Ready to read sensor data.")
            elif jobItem['probe2'] == True:
               self.measureJobState = 4
               self.resultPage.textBrowser.append("==> Ready to read sensor data.")
            else:
               self.measureJobState = 5
               self.resultPage.textBrowser.append("==> Go to next step.")

      elif self.measureJobState == 3:
         '''
         Read value of Probe1 for every sample
         '''
         if jobItem['probe1'] == True:
            self.ReadSensor1Data(jobItem)

            if self.readSensorDataDone == True:
               self.measureJobState = 4
               self.readSensorDataDone = False
               self.sampleReadIndex = 0
               self.sensorDataState = 0
         else:
            self.measureJobState = 4

      elif self.measureJobState == 4:
         '''
         Read value of probe2 for every sample
         '''
         if jobItem['probe2'] == True:
            self.ReadSensor2Data(jobItem)

            if self.readSensorDataDone == True:
               self.measureJobState = 5
               self.readSensorDataDone = False
         else:
            self.measureJobState = 5

      elif self.measureJobState == 5:
         '''
         Get next measure job index
         '''
         self.resultPage.textBrowser.append("==============================Cycle=%d, Step=%d"%(self.measureRepeatTimes,self.measureJobIndex))
         print("==============================Cycle=%d, Step=%d"%(self.measureRepeatTimes,self.measureJobIndex))

         if (self.measureJobIndex == self.testCfg.measureJobRepeat['stopIndex']
         and self.measureRepeatTimes != self.testCfg.measureJobRepeat['repeatTimes']):
            self.measureRepeatTimes = self.measureRepeatTimes + 1
            self.measureJobIndex = self.testCfg.measureJobRepeat['startIndex']
            self.measureJobState = 0
            self.readBackTemp1 = 0.0
         elif self.measureJobIndex != len(self.testCfg.measureJobList) - 1:
            # go to next measure cycle
            self.measureJobIndex = self.measureJobIndex + 1
            self.measureJobState = 0
         else:
            # go to next test job
            self.testJobStat = 5

   def ReadSensor1Data(self, jobItem):
      self.ReadSensorData(jobItem, self.testCfg.MeasureParameter['Move1M'], self.testCfg.MeasureParameter['Move1N'], 1)

   def ReadSensor2Data(self, jobItem):
      self.ReadSensorData(jobItem, self.testCfg.MeasureParameter['Move2M'], self.testCfg.MeasureParameter['Move2N'], 2)

   def ReadSensorData(self, jobItem, ParaM, ParaN, Probe):
      if self.sensorDataState == 0:
         '''
         Move the probe1 to position for the sample to measure
         '''
         if self.testCfg.sampleTypeList[self.sampleReadIndex] == 0:
            self.sensorDataState = 3
            return

         position = ParaM * self.sampleReadIndex + ParaN

         try:
            Stm32.serialwork.sendData(Stm32.sendMoveTo(position))
            self.probeMoveDone = False
            self.sensorDataState = 1
            self.resultPage.textBrowser.append("====> move sensor to the sample %d"%self.sampleReadIndex)

         except:
            print(" Send cmd moveTo error!")
      elif self.sensorDataState == 1:
         '''
         Check if response of move cammand is received
         '''
         if self.probeMoveDone == True:
            if Probe == 1:
               Probe1.readDataWithFilter()
               self.dataProbe1 = -100
            else:
               Probe2.readDataWithFilter()
               self.dataProbe2 = -100
            print("cycle %d, probe %d: probe is ready to read sample %d ."%(self.measureRepeatTimes, Probe, self.sampleReadIndex))

            self.sensorDataState = 2
         else:
            # todo, add an error counter here
            print("probe is moving to sample %d ."%self.sampleReadIndex)
      elif self.sensorDataState == 2:
         '''
         Read sensor data for this sample
         '''
         if Probe == 1:
            if self.dataProbe1 > 0:
               self.resultPage.textBrowser.append("Probe1 data for smaple %d, %f"%(self.sampleReadIndex, self.dataProbe1))
               self.resultPage.PCR1.AddPointToCurve(self.sampleReadIndex, self.dataProbe1)
               self.sensorDataState = 3
         else:
            if self.dataProbe2 > 0:
               self.resultPage.textBrowser.append("Probe2 data for smaple %d, %f"%(self.sampleReadIndex, self.dataProbe2))
               self.resultPage.PCR2.AddPointToCurve(self.sampleReadIndex, self.dataProbe2)
               self.sensorDataState = 3
      elif self.sensorDataState == 3:
         '''
         Get next sample to measure
         '''
         if self.sampleReadIndex != 7:
            self.sampleReadIndex = self.sampleReadIndex + 1
            self.sensorDataState = 0
         else:
            # it will go to measre probe2
            self.readSensorDataDone = True
            self.sampleReadIndex = 0

   def processMelting(self):
      print("melting...")

   def isTemp2Reached(self, temp2):
      tempMax = self.testCfg.TempHotCover + self.testCfg.MeasureParameter['Temp2Err']
      tempMin = self.testCfg.TempHotCover - self.testCfg.MeasureParameter['Temp2Err']
      if temp2 < tempMax and temp2 > tempMin:
         return True
      else:
         return False

   def isTemp1Reached(self, temp1, targetTemp):
      tempMax = targetTemp + self.testCfg.MeasureParameter['Temp1Err']
      tempMin = targetTemp - self.testCfg.MeasureParameter['Temp1Err']
      if temp1 < tempMax and temp1 > tempMin:
         return True
      else:
         return False

   def stopTest(self):
      self.jobTimer.stop()
      self.resultPage.clearResult()
      try:
         Stm32.serialwork.sendData(Stm32.sendCmdReset())
         print("Test done! send cmd 'reset' to stm32...")
      except:
         print('send reset cmd error!')


if __name__ == "__main__":

   import sys
   App = QtWidgets.QApplication(sys.argv)
   appWin = Window()

   if sys.platform == 'linux':
      appWin.portNameProbe1 = "/dev/ttySAC2"
      appWin.portNameProbe2 = "/dev/ttySAC3"
      appWin.portNameStm32 = "/dev/ttySAC4"

   Probe1 = SerialProbe(_port=appWin.portNameProbe1)
   Probe1.setRcvCallBack(appWin.readRcvProbe1)

   Probe2 = SerialProbe(_port=appWin.portNameProbe2)
   Probe2.setRcvCallBack(appWin.readRcvProbe2)

   Stm32 = SerialStm32(_port=appWin.portNameStm32)
   Stm32.setRcvCallBack(appWin.readRcvStm32)

   App.exec()